/**
 * Copyright 2006 gworks.com.au
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. (http://www.apache.org/licenses/LICENSE-2.0)
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed 
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for 
 * the specific language governing permissions and limitations under the License.
 *
 * <dhamma-message src="Atisha (11th century Tibetan Buddhist master)">
 * 	The greatest achievement is selflessness. The greatest worth is self-mastery.
 * 	The greatest quality is seeking to serve others. The greatest precept is continual awareness.
 * 	The greatest medicine is the emptiness of everything. The greatest action is not conforming with the worlds ways.
 * 	The greatest magic is transmuting the passions. The greatest generosity is non-attachment.
 * 	The greatest goodness is a peaceful mind. The greatest patience is humility.
 * 	The greatest effort is not concerned with results. The greatest meditation is a mind that lets go.
 * 	The greatest wisdom is seeing through appearances. 
 * </dhamma-message>
 */
package org.javaongems.server;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

/**
 * <p>Provides the ability to query the user principal if the user entered a secured
 * context atleast once during their http session.</p>
 * <p>Responsibilities:
 * <ul>
 * 	<li> fetch the principal from the http request object if using a secured context
 * 	<li> fetch the principal from the http session object if using unsecured 
 * 		context and previously visied a secured context
 * 	<li> fetch the default guest principal if no other options
 * </ul>
 * </p>
 * <p>Collaborators:
 * <ul>
 * 	<li> {@link HttpServletRequest}
 * 	<li> {@link HttpSession}
 * </ul>
 * </p>
 * @author Ashin Wimalajeewa (ash)
 */
final public class PrincipalUtils {
	final static private Logger LOGGER = Logger.getLogger(PrincipalUtils.class);
	final static public String SESS_PRINCIPAL = "gems.session.principal-object";
	final static DefaultPrincipal guestPrincipal = new DefaultPrincipal("guest");

	private PrincipalUtils() {
		// nothing to do.
	}

	static public Principal getPrincipal(HttpServletRequest req) {
		HttpSession session = req.getSession();

		Principal ret = req.getUserPrincipal();
		if (ret == null) {
			if (LOGGER.isDebugEnabled()) LOGGER.debug("using unsecured context.");
			ret = (Principal) session.getAttribute(SESS_PRINCIPAL);
			if (ret == null) {
				ret = guestPrincipal;
				if (LOGGER.isDebugEnabled()) LOGGER.debug("using guest principal.");
			} else
				if (LOGGER.isDebugEnabled()) LOGGER.debug("using session principal on previous secured context.");
		} else {
			HttpPrincipal hp = new HttpPrincipal(ret, req);
			ret = hp;
			session.setAttribute(SESS_PRINCIPAL, hp);
			if (LOGGER.isDebugEnabled()) LOGGER.debug("updated session principal on secured context.");
		}
		return ret;
	}

	static public boolean isVisitorPrincipal(Principal toChk) {
		return (toChk instanceof DefaultPrincipal);
	}

	static public class HttpPrincipal implements Principal {
		private Principal delegate;

		public HttpPrincipal(Principal toWrap, HttpServletRequest roleSrc) {
			delegate = toWrap;
		}

		public boolean equals(Object another) {
			return false;
		}

		public String getName() {
			return delegate.getName();
		}

		public String toString() {
			return delegate.toString();
		}
	}

	static public class DefaultPrincipal implements Principal {
		private String name;

		public DefaultPrincipal(String nm) {
			name = nm;
		}

		public boolean equals(Object another) {
			return false;
		}

		public String getName() {
			return name;
		}

		public int hashCode() {
			return name.hashCode();
		}

		public String toString() {
			return name;
		}
	}
}